#!/usr/bin/env python
#-*-encoding:utf-8-*-
'''
Created on 2014年7月30日

@author: chenyongbing
'''
import commands
import os,datetime,sys,time

import argparse,re

class RedisClear(object):
    '''
    classdocs
    '''


    def __init__(self,host='localhost',port=6379,rpath=None,testing=False):
        '''
        Constructor
        '''
        self.host = host
        self.port = int(port)
        self.testing = testing
        self.rpath = rpath
    def clearByDay(self,string=None,ago=3):
        if self.rpath:
            cmd = rpath+'/src/'
        else:
            cmd = ''
        cmd = cmd+'redis-cli -h %s -p %s keys "*"'%(self.host,self.port)
        if string ==None:
            cmd = cmd + ' | grep "[0-9]\{4\}-[0-9]\{2\}-[0-9]\{2\}"'
            #day = (datetime.date.today()-datetime.timedelta(ago)).strftime('%Y-%m-%d')
            i= 0
            while i<=ago:
                dtime = (datetime.date.today()-datetime.timedelta(i)).strftime('%Y-%m-%d')
                cmd = cmd + ' | grep -v "%s"'%(dtime)
                i+=1
        else:
            cmd = cmd + ' | grep "%s"'%string
        
        if self.testing==False:
            if self.rpath:
                cmd = cmd + ' | xargs %s/src/redis-cli -h %s -p %s del'%(self.rpath,self.host,self.port)
            else:
                cmd = cmd + ' | xargs redis-cli -h %s -p %s del'%(self.host,self.port)
        else:
            print cmd
            cmd = cmd + ' | wc -l'
            
        try:
            #out = os.popen(cmd).read().strip()
            out = commands.getoutput(cmd).strip()
        except:
            print "CRITICAL - cmd  running error."
            sys.exit(2)
        try:
            if len(out)==0:
                delCount = 0
            else:
                delCount = 0
                for line in out.split('\n'):
                    line = line.strip()
                    delCount += int(line)
        except:
            print 'CRITICAL - %s'%out
            sys.exit(2)
        if self.testing:
            print 'OK - scan %s key from %s:%s'%(delCount,self.host,self.port)
        else:
            print 'OK - del %s key from %s:%s'%(delCount,self.host,self.port)
        
        sys.exit(0)
        
        
if __name__=="__main__":
    parser = argparse.ArgumentParser(description='args')
    parser.add_argument('-H',metavar=u"redis host",required=True)
    parser.add_argument('-P', metavar=u'redis port', default=6379,type=int)
    parser.add_argument('--path', metavar=u'redis path', default=None)
    parser.add_argument('--ago', metavar=u'delete ago', default=1,type=int)
    parser.add_argument('--keys', metavar=u'keys ', default=None)
    parser.add_argument('--testing',action='store_true',help='testing')
    args = parser.parse_args()
    host = args.H
    port = args.P
    string = args.keys
    testing = args.testing
    rpath = args.path
    ago = args.ago
    myRedisClear = RedisClear(host=host,port=port,rpath=rpath,testing=testing)
    myRedisClear.clearByDay(string=string,ago=ago)
    